package com.huan.hystrix.service.impl;

import com.huan.hystrix.entity.Product;
import com.huan.hystrix.service.ProductService;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author huan.fu
 * @date 2018/8/8 - 15:26
 */
@Service
public class ProductServiceImpl implements ProductService {

	private static final String PRODUCT_URL = "http://localhost:9099/product/%s";

	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().stream()
				.forEach(converter -> {
					if (converter instanceof StringHttpMessageConverter) {
						((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
					}
				});
		return restTemplate;
	}

	@Override
	public Product selectOne(String productId) {
		return restTemplate().getForObject(String.format(PRODUCT_URL, productId), Product.class);
	}
}
